package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.common.exception.BusinessException;
import com.demo.pojo.dto.CourseListDTO;
import com.demo.pojo.entity.Course;
import com.demo.service.CourseService;
import com.demo.mapper.CourseMapper;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 课程服务实现类
 * @author lenovo
 * @description 针对表【course】的数据库操作Service实现
 * @createDate 2025-09-11 17:15:14
 */
@Service
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    private final CourseMapper courseMapper;

    public CourseServiceImpl(CourseMapper courseMapper) {
        this.courseMapper = courseMapper;
    }

    @Override
    public Course selectById(Long id) {
        //根据课程id查询课程信息
        Course course = courseMapper.selectById(id);
        //如果没查到抛出异常
        if (course == null){
            throw new BusinessException("没有此课程信息");
        }
        log.info("查询课程信息成功:{}", course);
        return course;
    }

    @Override
    public void saveCourse(Course course) {
        // 验证必填字段
        if (course.getCoName() == null || course.getCoName().trim().isEmpty()) {
            throw new BusinessException("课程名称不能为空");
        }
        if (course.getCoCredit() == null) {
            throw new BusinessException("课程学分不能为空");
        }
        if (course.getCoType() == null || course.getCoType().trim().isEmpty()) {
            throw new BusinessException("课程类型不能为空");
        }
        
        //新增前判断课程名称有无重复
        if (courseMapper.selectByName(course.getCoName()) != null){
            throw new BusinessException("课程名称重复");
        }
        
        // 设置创建时间
        course.setCoUpdateDate(new Date());
        
        //执行新增操作
        int result = courseMapper.insert(course);
        if (result <= 0) {
            throw new BusinessException("新增课程失败");
        }
        log.info("新增课程信息成功:{}", course);
    }

    @Override
    public void updateCourse(Course course) {
        // 验证必填字段
        if (course.getCoName() == null || course.getCoName().trim().isEmpty()) {
            throw new BusinessException("课程名称不能为空");
        }
        if (course.getCoCredit() == null) {
            throw new BusinessException("课程学分不能为空");
        }
        if (course.getCoType() == null || course.getCoType().trim().isEmpty()) {
            throw new BusinessException("课程类型不能为空");
        }
        
        //修改前判断是否存在该课程
        Course oldCourse = courseMapper.selectById(course.getCoId());
        if (oldCourse == null){
            throw new BusinessException("没有此课程信息");
        }
        //修改前判断课程名称有无变动
        //如果查询出的课程名称和修改前的课程名称一致，则不进行修改
        if (!oldCourse.getCoName().equals(course.getCoName())){
           //课程名称不一致，说明课程名称被修改，查询有无重复
            if (courseMapper.selectByName(course.getCoName()) != null){
                throw new BusinessException("课程名称重复");
            }
        }
        
        //设置修改时间
        course.setCoUpdateDate(new Date());
        
        //执行修改操作
        int result = courseMapper.updateById(course);
        if (result <= 0) {
            throw new BusinessException("修改课程失败");
        }
        log.info("修改课程信息成功:{}", course);
    }
    @Override
    public Map<String, Object> listPage(CourseListDTO dto) {
        // 1. 创建分页对象
        Page<Course> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        // 2. 构建查询条件
        //    ✅ 仅当字段有效时才添加查询条件，避免 -1 或无效值干扰
        LambdaQueryWrapper<Course> lambdaQueryWrapper = new LambdaQueryWrapper<Course>()
                // 课程名称：非空才查
                .like(StringUtils.isNotBlank(dto.getCoName()), Course::getCoName, dto.getCoName())
                // 课程学分：不为 null 且大于 0 才查
                .eq(dto.getCoCredit() != null && dto.getCoCredit() > 0, Course::getCoCredit, dto.getCoCredit())
                // 课程类型：非空且不等于 "-1"（前端“全部”选项的占位值）才查
                .like(StringUtils.isNotBlank(dto.getCoType()) && !"-1".equals(dto.getCoType()), Course::getCoType, dto.getCoType())
                // 备注：非空才查
                .like(StringUtils.isNotBlank(dto.getCoRemark()), Course::getCoRemark, dto.getCoRemark());

        // 3. 执行分页查询
        Page<Course> pageResult = courseMapper.selectPage(page, lambdaQueryWrapper);

        log.info("分页查询结果：总记录数={}, 当前页数据数量={}", pageResult.getTotal(), pageResult.getRecords().size());

        // 4. 返回标准分页结果
        return Map.of(
                "records", pageResult.getRecords(),   // 当前页数据
                "total", pageResult.getTotal(),      // 总记录数
                "current", pageResult.getCurrent()   // 当前页码
        );
    }

    @Override
    public List<CourseListDTO> getCourseList() {
        // 查询所有课程
        List<Course> courses = list();
        List<CourseListDTO> courseListDTOs = new ArrayList<>();
        
        for (Course course : courses) {
            CourseListDTO dto = new CourseListDTO();
            dto.setCoName(course.getCoName());
            dto.setCoCredit(course.getCoCredit());
            dto.setCoType(course.getCoType());
            dto.setCoRemark(course.getCoRemark());
            courseListDTOs.add(dto);
        }
        
        return courseListDTOs;
    }
}


